package num52;

/**
 * @author : DuJiabao
 * @Date : 2021/1/25 14:21
 * @Project : sword-finger-offer
 * @File : null.java
 * @Desc : 两个链表的第一个公共结点
 * https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/
 * 解法一： 首先获取当前两个链表的长度，然后长的那个链表先走比短的那个链表长的距离。随后，两个链表一起走，直到相遇。
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode pointA = headA;
        ListNode pointB = headB;
        int lengthA = 0, lengthB = 0;
        while (headA != null) {
            lengthA++;
            headA = headA.next;
        }
        while (headB != null) {
            lengthB++;
            headB = headB.next;
        }
        headA = pointA;
        headB = pointB;
        if (lengthA > lengthB) {
            for (int i = 0; i < lengthA - lengthB; i++) {
                headA = headA.next;
            }
        } else if (lengthA < lengthB) {
            for (int i = 0; i < lengthB - lengthA; i++) {
                headB = headB.next;
            }
        }
        while (headA != null && headB != null) {
            if (headA == headB) return headA;
            headA = headA.next;
            headB = headB.next;
        }
        return null;
    }
}
